package com.azusa.xbiao.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * 用于发送邮箱验证码
 */
@Component
public class EmailUtil {

    //邮件发送人
    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender mailSender;

    /**
     * 发送邮件
     * @param to  接收人
     * @param subject 邮件标题
     * @param verifyCode 验证码
     */
    public void sendMail(String to, String subject, String verifyCode) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText("您的验证码为：" + verifyCode + "，有效期10分钟"); //邮件内容
        try {
            mailSender.send(message);
            System.out.println("邮箱发送成功");
        } catch (MailException e) {
            e.printStackTrace();
            System.out.println("邮箱发送失败");
        }
    }

    public String getCode(int length){
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<length;i++){
            int number=random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }
}
